
// Definition for a binary tree node.
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

#include <queue>
using namespace std;
class Solution
{
public:
    vector<int> rightSideView(TreeNode *root)
    {
        if (!root)
            return {};
        vector<int> res;
        queue<TreeNode *> que;
        que.push(root);
        while (!que.empty())
        {
            int level_size = que.size();
            // 遍历每层
            for (int i = 0; i < level_size; i++)
            {
                TreeNode *node = que.front();
                int val = node->val;
                que.pop();
                if (i == level_size - 1)
                    res.push_back(val);
                if (node->left)
                    que.push(node->left);
                if (node->right)
                    que.push(node->right);
            }
        }
        return res;
    }
};